<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Writing our own Class in Ruby: Ruby Study Notes - Best Ruby Guide, Ruby Tutorial</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="Ruby Study Notes - Best Ruby Guide, Ruby Tutorial" />
<meta name="keywords" content="ruby study notes,writing our own class in ruby,literal constructors,garbage collection,class methods,ruby tutorials,ruby tutorial,learn ruby,ruby,ruby on rails,ruby rails,ruby learning,ruby tutoring,learning ruby,ruby programming,ruby on rails development,ruby training" />
<meta name="Distribution" content="Global" />
<meta name="author" content="Satish Talim / Original design: Erwin Aligam - ealigam@gmail.com" />
<meta name="copyright" content="Satish Talim 2007 and beyond..." />
<meta name="verify-v1" content="rFu86se+IkbtF+bH8mgJBKwU5HnKaSd8Ghw9umXQOkM=" />
<meta name="robots" content="index,follow" />
<meta http-equiv="Expires" content="0" />
<meta name="revisit-after" content="1 days" />
<link rel="stylesheet" href="/images/NewOrange.css" type="text/css" />
<link rel="stylesheet" href="/images/syntaxhighlighter.css" type="text/css" />
<link rel="icon" type="image/ico" href="/images/favicon.ico" />
<!-- Google +1 button code -->
<link rel="canonical" href="/satishtalim/writing_our_own_class_in_ruby.html" />
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>

<!-- Google Analytics code -->
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-59044-10']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<!-- Google Analytics code ends -->
</head>

<body>
<!-- wrap starts here -->
<div id="wrap">

    <div id="header">

        <h1 id="logo">Ruby<span class="orange">Learning.github.io</span></h1>
        <h2 id="slogan">Helping Ruby Programmers become Awesome!</h2>

    </div>

    <div id="menu">
        <ul>
            <li><a href="/" title="Home page for rubylearning.github.io">Home</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Get started Learning Ruby here...">Tutorial</a></li>
            <li><a href="/download/downloads.html" title="Download this tutorial as an eBook">Downloads</a></li>
            <li><a href="/other/testimonials.html" title="People around the world who benefited from this site">Testimonials</a></li>
            <li><a href="/other/certification.html" title="Get certified in Ruby">Certification</a></li>
            <li><a href="/satishtalim/ruby_guide.html" title="Ruby Guide, Mentor">Mentor</a></li>
            <li><a href="https://blog.rubylearning.github.io/" title="Ruby blog of Learning Ruby site">Blog</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Online Ruby Course">Online Course</a></li>
            <li><a href="http://ruby-challenge.rubylearning.github.io/" title="Ruby Programming Challenge for Newbies">Challenge</a></li>
            <li><a href="/satishtalim/about.html" title="Information about Satish Talim">About</a></li>
        </ul>
    </div>

    <!-- content-wrap starts here -->
    <div id="content-wrap">

            <div id="main">

                <div id="main-inner"><a name="TemplateInfo"></a>
                <h1>Writing our own Class in Ruby</h1>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/ruby_regular_expressions.html">&lt;Regular Expressions | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/ruby_method_missing.html">Method Missing&gt;</a>
                  </strong>
                </p>

                <p>So far, the procedural style of programming (this continues to be used in languages such as C) was used to write our programs. Programming procedurally means you focus on the steps required to complete a task without paying particular attention to how the data is managed.</p>

                <p>In the Object-Orientation style, objects are your agents, your proxies, in the universe of your program. You ask them for information. You assign them tasks to accomplish. You tell them to perform calculations and report back to you. You hand them to each other and get them to work together.
                </p>

                <p>When you design a class, think about the objects that will be created from that class type. Think about the things the object <strong>knows</strong> and the things the object <strong>does</strong>.</p>

                <p>Things an object <strong>knows</strong> about itself are called <i>instance variables</i>. They represent an object's state (the data - for example, the quantity and the product id), and can have unique values for each object of that type.</p>

                <p>Things an object can <strong>do</strong> are called <i>methods</i>.</p>

                <blockquote><p>An object is an entity that serves as a container for data and also controls access to the data. Associated with an object is a set of attributes, which are essentially no more than variables belonging to that object. Also associated with an object is a set of functions that provide an interface to the functionality of the object, called methods. - Hal Fulton</p></blockquote>

                <p>An object is a combination of state and methods that use the state.</p>

                <p>Hence a class is used to construct an object. A class is a blueprint for an object. For example, you might use a Button class to make dozens of different buttons, and each button might have its own color, size, shape, label, and so on. An object is an instance of a class.</p>

                <p class="post-note">
                <strong>Read this very carefully, it's a brain bender!</strong><br />Classes in Ruby are first-class objects - each is an instance of class <strong>Class</strong>. When a new class is defined (typically using <strong>class</strong> Name ... <strong>end</strong>), an object of type <strong>Class</strong> is created and assigned to a constant (Name. in this case). When Name.<strong>new</strong> is called to create a new object, the <strong>new</strong> class method in <strong>Class</strong> is run by default, which in turn invokes <strong>allocate</strong> to allocate memory for the object, before finally calling the new object's <strong>initialize</strong> method. The constructing and initializing phases of an object are separate and both can be over-ridden. The construction is done via the <strong>new</strong> class method, the initialization is done via the <strong>initialize</strong> instance method. <strong>initialize</strong> is not a constructor!</p>

                <p>The following class hierarchy (courtesy: <a href="http://skilldrick.co.uk/2011/08/understanding-the-ruby-object-model/">Nick Morgan</a>) is informative:</p>

                <p><a href="/images/rubyclass.jpg" title="Class Hierarchy"><img src="/images/rubyclass.jpg" alt="Class Hierarchy" /></a></p>

                <p>Let's write our first, simple class - <strong>p029dog.rb</strong></p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p029dog.rb
                # define class Dog
                class Dog
                  def initialize(breed, name)
                    # Instance variables
                    @breed = breed
                    @name = name
                  end

                  def bark
                    puts 'Ruff! Ruff!'
                  end

                  def display
                    puts "I am of #{@breed} breed and my name is #{@name}"
                  end
                end

                # make an object
                # Objects are created on the heap
                d = Dog.new('Labrador', 'Benzy')

                =begin
                  Every object is "born" with certain innate abilities.
                  To see a list of innate methods, you can call the methods
                  method (and throw in a sort operation, to make it
                  easier to browse visually). Remove the comment and execute.
                =end
                # puts d.methods.sort

                # Amongst these many methods, the methods object_id and respond_to? are important.
                # Every object in Ruby has a unique id number associated with it
                puts "The id of d is #{d.object_id}."

                # To know whether the object knows how to handle the message you want
                # to send it, by using the respond_to? method.
                if d.respond_to?("talk")
                  d.talk
                else
                  puts "Sorry, d doesn't understand the 'talk' message."
                end

                d.bark
                d.display

                # making d and d1 point to the same object
                d1 = d
                d1.display

                # making d a nil reference, meaning it does not refer to anything
                d = nil
                d.display

                # If I now say
                d1 = nil
                # then the Dog object is abandoned and eligible for Garbage Collection (GC)
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The output is:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                >ruby p029dog.rb
                The id of d is 22982920.
                Sorry, d doesn't understand the 'talk' message.
                Ruff! Ruff!
                I am of Labrador breed and my name is Benzy
                I am of Labrador breed and my name is Benzy
                >Exit code: 0
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The method <strong>new</strong> is used to create an object of class Dog. Objects are created on the heap. The variable d is known as a reference variable. It does not hold the object itself, but it holds something like a pointer or an address of the object. You use the dot operator (.) on a reference variable to say, "use the thing before the dot to get me the thing after the dot." For example:<br /><strong>d.bark</strong></p>

                <p class="post-note">
                <strong>IN RAILS</strong>: If you're writing a Rails application in which one of your entity models is, say, Customer, then when you write the code that causes things to happen - a customer logging into a site, updating a customer's phone number, adding an item to a customer's shopping cart - in all likelihood you'll be sending messages to customer objects.
                </p>

                <p>Even a newly created object isn't a blank slate. As soon as an object comes into existence, it already responds to a number of messages. Every object is "born" with certain innate abilities. To see a list of innate methods, you can call the <strong>methods</strong> method (and throw in a <strong>sort</strong> operation, to make it easier to browse visually):<br /><strong>puts d.methods.sort</strong><br />The result is a list of all the messages (methods) this newly minted object comes bundled with. Amongst these many methods, the methods <strong>object_id</strong> and <strong>respond_to?</strong> are important.</p>

                <p>Every object in Ruby has a unique id number associated with it. You can see an object's id by asking the object to show you its <strong>object_id:<br />puts "The id of d is #{d.object_id}."</strong></p>

                <p>You can determine in advance (before you ask the object to do something) whether the object knows how to handle the message you want to send it, by using the <strong>respond_to?</strong> method. This method exists for all objects; you can ask any object whether it responds to any message. <strong>respond_to?</strong> usually appears in connection with conditional (if) logic.</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                if d.respond_to?("talk")
                  d.talk
                else
                  puts "Sorry, the object d doesn't understand the 'talk' message."
                end
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Now, the statements:<br /><strong>d1 = d<br />d1.display</strong><br />makes d and d1 point to the same object.</p>

                <p>You can ask any object of which class it's a member by using its <strong>Object.class</strong> method. In the above program, if we write the statement:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                d = Dog.new('Alsatian', 'Lassie')
                puts d.class.to_s
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The output is:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                >ruby p029dog.rb
                Dog
                >Exit code: 0
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p><strong>instance_of?</strong> returns true if object is an instance of the given class, as in this example:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                num = 10
                puts(num.instance_of? Fixnum) # output true
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Often, it is better to ask <b>respond_to?</b> rather than <b>instance_of?</b> as we usually care about 'ability' rather than 'type'.</p>

                <h3>Literal Constructors</h3>

                <p>That means you can use special notation, instead of a call to <strong>new</strong>, to create a new object of that class. The classes with literal constructors are shown in the table below. When you use one of these literal constructors, you bring a new object into existence</p>
                <p><b>Examples</b>:</p>
                <p>String - 'hello' or "hello"<br />Symbol - :symbol or :"hello world"<br />Array - [x, y, z]<br />Hash - {"India" => "IN"}<br />Range - 3..7 or 3...7</p>
                <p>Observe that there is no visible call to <b>new</b>.</p>

                <h3>Garbage Collection</h3>

                <p>The statement:<br />d =nil<br />makes d a <strong>nil</strong> reference, meaning it does not refer to anything. If I now say:<br />d1 = nil<br />then the Dog object is abandoned and eligible for <strong>Garbage Collection</strong> (GC). The Ruby object heap allocates a minimum of <i>8 megabytes</i>. Ruby's GC is called <i>mark-and-sweep</i>. The "mark" stage checks objects to see if they are still in use. If an object is in a variable that can still be used in the current scope, the object (and any object inside that object) is marked for keeping. If the variable is long gone, off in another method, the object isn't marked. The "sweep" stage then frees objects which haven't been marked.</p>

                <p>Ruby uses a conservative mark-and-sweep GC mechanism. There is no guarantee that an object will undergo garbage collection before the program terminates.</p>

                <h3>Class Methods</h3>

                <p>The idea of a class method is that you send a message to the object that is the class rather than to one of the class's instances. Class methods serve a purpose. Some operations pertaining to a class can't be performed by individual instances of that class. <strong>new</strong> is an excellent example. We call Dog.new because, until we've created an individual dog instance, we can't send it any messages! Besides, the job of spawning a new object logically belongs to the class. It doesn't make sense for instances of Dog to spawn each other. It does make sense, however, for the instance-creation process to be centralized as an activity of the class Dog. It's vital to understand that by Dog.new, we have a method that we can access through the class object Dog but not through its instances. Individual dog objects (instances of the class Dog) do not have this method. A class object (like Dog) has its own methods, its own state, its own identity. It doesn't share these things with instances of itself.</p>

                <p>Here's an example:</p>
                <p><b>Dog#bark</b> - the instance method <b>bark</b> in the class <b>Dog</b><br /><b>Dog.color</b> - the class method <b>color</b>, in the class <b>Dog</b><br /><b>Dog::color</b> - another way to refer to the class method <b>color</b></p>

                <p>In writing about Ruby, the <em>pound notation</em> (#) is sometimes used to indicate an instance method - for example, we say <strong>File.chmod</strong> to denote the class method <strong>chmod</strong> of class <strong>File</strong>, and <strong>File#chmod</strong> to denote the instance method that has the same name. <strong>This notation is not part of Ruby syntax.</strong></p>

                <p>You will learn how to write class methods, later on <a href="/satishtalim/ruby_constants.html" >here</a>.</p>

                <p style="background-color: #FAFAFA; padding: 5px; margin-top: 20px; font-size: 65%;"><strong>Note</strong>: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various <span style="font-weight: bold;" title="Click Gurus on the menu above">Ruby Gurus</span>), my acknowledgment and thanks to all of them. Much of the material on <a href="/">rubylearning.github.io</a> and in the course at <a href="http://rubylearning.org/">rubylearning.org</a> is drawn <strong>primarily</strong> from the <strong>Programming Ruby book</strong>, available from <a href="http://pragprog.com/book/ruby3/programming-ruby-1-9-2-0">The Pragmatic Bookshelf</a>.</p>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/ruby_regular_expressions.html">&lt;Regular Expressions | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/ruby_method_missing.html">Method Missing&gt;</a>
                  </strong>
                </p>

            </div>
            <!-- main inner ends here -->
        </div>

            <div id="rightbar">
            </div>

    <!-- content-wrap ends here -->
    </div>

<!-- wrap ends here -->
</div>

<!-- footer starts here -->
<div id="footer">
    <!-- CHANGE THE FOOTER -->
    <p>&copy; 2006-2021 <strong>rubylearning.github.io - A Ruby Tutorial</strong>&nbsp;&nbsp;Page Updated: 5th Jan. 2021 | Design: <a href="mailto:ealigam@gmail.com">Erwin Aligam</a> | Valid: <a href="http://validator.w3.org/check/referer">XHTML</a> | <a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="/">Home</a> | <a href="/privacy.html">Privacy</a> | <a href="/sitemap.html">Sitemap</a></p>
</div>

<!-- footer ends here -->

<!-- SyntaxHighlighter code -->
<script src="/js/shCore.js" type="text/javascript"></script>
<script src="/js/shBrushRuby.js" type="text/javascript"></script>
<script type="text/javascript">
dp.SyntaxHighlighter.HighlightAll('code');
</script>
<!-- SyntaxHighlighter code -->
</body>
</html>
